const express = require('express');
const router = express.Router();
const { pool } = require('../config/db');

// 添加调试日志
console.log('departments路由模块已加载');

// 获取所有院系
router.get('/', async (req, res) => {
  try {
    console.log('收到获取院系列表请求');
    
    // 添加更多调试信息
    console.log('执行SQL查询: SELECT id, name FROM departments');
    
    const [rows] = await pool.query('SELECT id, name FROM departments');
    
    console.log('院系查询结果:', rows);
    
    // 返回结果
    res.json(rows);
  } catch (error) {
    console.error('获取院系列表失败:', error);
    res.status(500).json({ message: '服务器错误', error: error.message });
  }
});

// 获取院系详情
router.get('/:id', async (req, res) => {
  try {
    const [rows] = await pool.query('SELECT * FROM departments WHERE id = ?', [req.params.id]);
    
    if (rows.length === 0) {
      return res.status(404).json({ message: '院系不存在' });
    }
    
    res.json(rows[0]);
  } catch (error) {
    console.error('获取院系详情失败:', error);
    res.status(500).json({ message: '服务器错误', error: error.message });
  }
});

module.exports = router;